<template>
  <el-card class="admin-user-card">
    <el-container class="admin-user-container" style="height: 100%;">
      <!-- 搜索区域 - Header -->
      <el-header class="admin-user-header">
        <el-form class="admin-user-form">
          <el-form-item style="width: 20%">
            <el-input v-model="username" placeholder="账号" style="width: 100%"></el-input>
          </el-form-item>
          <el-form-item class="admin-user-filter--desktop" style="width: 15%">
            <el-select v-model="roles" placeholder="请选择角色" style="width: 100%">
              <el-option label="全选" value=""></el-option>
              <el-option label="白嫖" value="白嫖"></el-option>
              <el-option label="付费" value="付费"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="admin-user-filter--desktop" style="width: 15%">
            <el-select v-model="weeks" placeholder="请选择周数" style="width: 100%">
              <el-option label="全选" value=""></el-option>
              <el-option label="已过期" value="0"></el-option>
              <el-option label="未过期" value="1"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item style="width: 20%">
            <el-button type="primary" @click="getUserData" style="width: 100%">搜索</el-button>
          </el-form-item>
        </el-form>
        
        <!-- 手机端专用的紧凑布局 -->
        <div class="admin-user-form-mobile">
          <el-input v-model="username" placeholder="账号" class="mobile-input"></el-input>
          <el-button type="primary" @click="getUserData" class="mobile-button">搜索</el-button>
        </div>
      </el-header>

      <!-- 表格区域 - Main -->
      <el-main class="admin-user-main">
        <div ref="tableContainer" class="table-container-wrapper">
          <el-table
            ref="userTable"
            border
            stripe
            :data="tableData"
            style="width: 100%"
            :style="{ height: `${tableMaxHeight}px` }"
          >
            <el-table-column
              align="center"
              fixed="left"
              label="序号"
              type="index"
              width="60">
            </el-table-column>
            <el-table-column
              fixed="left"
              align="center"
              width="150"
              prop="username"
              label="账号">
            </el-table-column>
            <el-table-column
              align="center"
              width="300"
              label="周数">
              <el-table-column
                align="center"
                label="-1">
                <template #default="{ row }">
                  <el-link :underline="false" @click="cutWeeks(row)">
                    <span style="font-size: 22px; color: red; font-weight: bold">-1</span>
                  </el-link>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="weeks"
                label="周数">
              </el-table-column>
              <el-table-column
                align="center"
                label="+1">
                <template #default="{ row }">
                  <el-link :underline="false" @click="addWeeks(row)">
                    <span style="font-size: 22px; color: green; font-weight: bold">+1</span>
                  </el-link>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column
              fixed="left"
              prop=""
              width="80"
              label="操作"
              align="center">
              <template #default="{ row }">
                <el-link :underline="false" @click="showUpdateForm(row)">
                  <span style="font-size: 18px; color: #67c23a; font-weight: bold">编辑</span>
                </el-link>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              width="60"
              prop="id"
              label="id">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="password"
              label="密码">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="nickname"
              label="昵称">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="mac"
              label="mac">
            </el-table-column>
            <el-table-column
              align="center"
              width="60"
              prop="roles"
              label="角色">
            </el-table-column>

            <el-table-column
              align="center"
              width="100"
              prop="addPermissions"
              label="添加权限">
              <template #default="{ row }">
                <el-switch
                  v-model="row.addPermissions"
                  @change="addPermissionsChange(row)"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              width="100"
              prop="queryPermissions"
              label="查询权限">
              <template #default="{ row }">
                <el-switch
                  v-model="row.queryPermissions"
                  @change="queryPermissionsChange(row)"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              width="100"
              prop="registrationTime"
              label="注册时间">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="txOcrSecretId"
              label="txOcrSecretId">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="txOcrSecretKey"
              label="txOcrSecretKey">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="txGptSecretId"
              label="txGptSecretId">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="txGptSecretKey"
              label="txGptSecretKey">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="txGptModel"
              label="txGptModel">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="txAddress"
              label="txAddress">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="bdApiKey"
              label="bdApiKey">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="bdSecretKey"
              label="bdSecretKey">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="xfAppId"
              label="xfAppId">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="xfApiSecret"
              label="xfApiSecret">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="xfApiKey"
              label="xfApiKey">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="hsApiKey"
              label="hsApiKey">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="hsModel"
              label="hsModel">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="dpApiKey"
              label="dpApiKey">
            </el-table-column>
            <el-table-column
              align="center"
              width="50"
              prop="coordinate"
              label="方案">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="coordinate1"
              label="方案1">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="coordinate2"
              label="方案2">
            </el-table-column>
            <el-table-column
              align="center"
              width="180"
              prop="coordinate3"
              label="方案3">
            </el-table-column>
          </el-table>
        </div>
      </el-main>
      <el-footer class="admin-user-footer">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @next-click="handleNextClick"
          @prev-click="handlePrevClick"
          background
          :current-page="page"
          layout="sizes, prev, pager, next,jumper,total"
          :page-size="10"
          :page-sizes="[10,20,50,100]"
          :total="total">
        </el-pagination>
      </el-footer>
    </el-container>
    <el-dialog title="修改用户" v-model="dialogFormVisible" :modal-append-to-body="false">
      <el-form :model="updateForm">
        <el-form-item label="id" :label-width="formLabelWidth">
          <el-input v-model="updateForm.id" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="昵称" :label-width="formLabelWidth">
          <el-input v-model="updateForm.nickname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="账号" :label-width="formLabelWidth">
          <el-input v-model="updateForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="updateForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="MAC" :label-width="formLabelWidth">
          <el-input v-model="updateForm.mac" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth">
          <el-select v-model="updateForm.roles" placeholder="请选择角色" style="width: 100%">
            <el-option label="白嫖" value="白嫖"></el-option>
            <el-option label="付费" value="付费"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="周数" :label-width="formLabelWidth">
          <el-input v-model="updateForm.weeks" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="update_user">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import apiClient from '@/utils/axios'
import { ElMessage } from 'element-plus'

interface UserRow {
  id: number
  username: string
  password: string
  nickname: string
  mac: string
  roles: string
  weeks: number
  addPermissions: boolean
  queryPermissions: boolean
  registrationTime: string
  txOcrSecretId: string
  txOcrSecretKey: string
  txGptSecretId: string
  txGptSecretKey: string
  txGptModel: string
  txAddress: string
  bdApiKey: string
  bdSecretKey: string
  xfAppId: string
  xfApiSecret: string
  xfApiKey: string
  hsApiKey: string
  hsModel: string
  dpApiKey: string
  coordinate: number
  coordinate1: string
  coordinate2: string
  coordinate3: string
}

interface UpdateForm {
  id: number | ''
  nickname: string
  username: string
  password: string
  mac: string
  roles: string
  weeks: number | ''
}

const page = ref<number>(1)
const pageSize = ref<number>(10)
const total = ref<number>(0)

const username = ref<string>('')
const roles = ref<string>('')
const weeks = ref<string>('')

const tableData = ref<UserRow[]>([])

const updateForm = reactive<UpdateForm>({
  id: '',
  nickname: '',
  username: '',
  password: '',
  mac: '',
  roles: '',
  weeks: '' as unknown as number,
})

const dialogFormVisible = ref<boolean>(false)
const formLabelWidth = '120px'

// 表格高度相关
const tableContainer = ref<HTMLElement | null>(null)
const userTable = ref<any>(null)
const tableMaxHeight = ref(500)

// 计算表格最大高度
const calculateTableMaxHeight = () => {
  if (!tableContainer.value) return

  const viewportHeight = window.innerHeight
  const containerTop = tableContainer.value.getBoundingClientRect().top
  const footerHeight = 60
  const reservedSpace = 20
  const availableHeight = viewportHeight - containerTop - footerHeight - reservedSpace

  tableMaxHeight.value = Math.max(availableHeight, 300)
}

// 监听窗口大小变化
const handleResize = () => {
  calculateTableMaxHeight()
}

const getUserData = () => {
  apiClient
    .get('/admin/query_user', {
      params: {
        page: page.value,
        pageSize: pageSize.value,
        username: username.value,
        roles: roles.value,
        weeks: weeks.value,
      },
    })
    .then((res) => {
      if (res.data.status === 200) {
        tableData.value = res.data.data.rows
        total.value = res.data.data.total
        ElMessage({
          message: res.data.msg,
          type: 'success',
          placement: 'top-right',
        })
      } else
        ElMessage({
          message: res.data.msg,
          type: 'error',
          placement: 'top-right',
        })
    })
    .catch((error) => {
      ElMessage({
        message: String(error),
        type: 'error',
        placement: 'top-right',
      })
    })
}

const addPermissionsChange = (row: UserRow) => {
  apiClient
    .get('/admin/update_add_permissions', {
      params: {
        id: row.id,
      },
    })
    .then((res) => {
      if (res.data.status === 200) {
        ElMessage({
          message: res.data.msg,
          type: 'success',
          placement: 'top-right',
        })
        getUserData()
      } else
        ElMessage({
          message: res.data.msg,
          type: 'error',
          placement: 'top-right',
        })
    })
    .catch((error) => {
      ElMessage({
        message: String(error),
        type: 'error',
        placement: 'top-right',
      })
    })
}

const queryPermissionsChange = (row: UserRow) => {
  apiClient
    .get('/admin/update_query_permissions', {
      params: {
        id: row.id,
      },
    })
    .then((res) => {
      if (res.data.status === 200) {
        ElMessage({
          message: res.data.msg,
          type: 'success',
          placement: 'top-right',
        })
        getUserData()
      } else
        ElMessage({
          message: res.data.msg,
          type: 'error',
          placement: 'top-right',
        })
    })
    .catch((error) => {
      ElMessage({
        message: String(error),
        type: 'error',
        placement: 'top-right',
      })
    })
}

const cutWeeks = (row: UserRow) => {
  apiClient
    .put('/admin/update_weeks', {
      id: row.id,
      username: row.username,
      weeks: -1,
    })
    .then((res) => {
      if (res.data.status === 200) {
        ElMessage({
          message: res.data.msg,
          type: 'success',
          placement: 'top-right',
        })
        getUserData()
      } else
        ElMessage({
          message: res.data.msg,
          type: 'error',
          placement: 'top-right',
        })
    })
}

const addWeeks = (row: UserRow) => {
  apiClient
    .put('/admin/update_weeks', {
      id: row.id,
      username: row.username,
      weeks: 1,
    })
    .then((res) => {
      if (res.data.status === 200) {
        ElMessage({
          message: res.data.msg,
          type: 'success',
          placement: 'top-right',
        })
        getUserData()
      } else
        ElMessage({
          message: res.data.msg,
          type: 'error',
          placement: 'top-right',
        })
    })
}

const showUpdateForm = (row: UserRow) => {
  updateForm.id = row.id
  updateForm.nickname = row.nickname
  updateForm.username = row.username
  updateForm.password = row.password
  updateForm.mac = row.mac
  updateForm.roles = row.roles
  updateForm.weeks = row.weeks
  dialogFormVisible.value = true
}

const update_user = () => {
  dialogFormVisible.value = false
  apiClient
    .put('/admin/update_user', updateForm)
    .then((res) => {
      if (res.data.status === 200) {
        ElMessage({
          message: res.data.msg,
          type: 'success',
          placement: 'top-right',
        })
        getUserData()
      } else
        ElMessage({
          message: res.data.msg,
          type: 'error',
          placement: 'top-right',
        })
    })
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  getUserData()
}

const handleCurrentChange = (val: number) => {
  page.value = val
  getUserData()
}

const handleNextClick = (val: number) => {
  page.value = val
  getUserData()
}

const handlePrevClick = (val: number) => {
  page.value = val
  getUserData()
}

onMounted(() => {
  getUserData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.admin-user-card {
  width: 100%;
  box-sizing: border-box;
}

.admin-user-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.admin-user-header {
  padding: 12px 16px;
  height: auto !important; /* 覆盖 Element Plus 默认 60px 高度 */
  overflow: visible;
}

.admin-user-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px 16px;
}

.admin-user-form :deep(.el-form-item) {
  flex: 1 1 180px;
  margin-right: 0;
}

/* 手机端专用布局默认隐藏 */
.admin-user-form-mobile {
  display: none;
}

.admin-user-main {
  padding: 0 8px 8px;
}

.admin-user-footer {
  padding: 8px 16px 12px;
  display: flex;
  justify-content: center;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .admin-user-card {
    margin: 0;
    border-radius: 0;
  }

  .admin-user-header {
    padding: 12px; /* 顶部整体 padding 适中 */
  }

  /* PC端表单在手机上隐藏 */
  .admin-user-form {
    display: none;
  }

  /* 显示手机端专用紧凑布局 */
  .admin-user-form-mobile {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    max-width: 320px;
    margin: 0 auto;
  }

  .mobile-input {
    width: 100%;
  }

  .mobile-button {
    width: 120px;
  }

  .admin-user-form .el-form-item {
    width: 100% !important;
    margin-right: 0;
  }

  /* 手机端隐藏"类型"和"过期"两个筛选条件，只保留账号和搜索按钮 */
  .admin-user-form .admin-user-filter--desktop {
    display: none;
  }

  .admin-user-form .el-input,
  .admin-user-form .el-select,
  .admin-user-form .el-button {
    width: 100% !important;
  }

  /* 调整输入框和按钮的尺寸 */
  .admin-user-form :deep(.el-input__wrapper) {
    padding: 8px 12px;
  }

  .admin-user-form :deep(.el-button) {
    padding: 10px 15px;
    font-size: 15px;
  }

  .admin-user-main {
    padding: 8px 4px 4px;
    overflow-x: auto; /* 整个 main 区域可横向滚动 */
  }

  /* 表格在小屏上的优化 */
  .admin-user-main :deep(.el-table) {
    font-size: 13px;
  }

  .admin-user-main :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }

  /* 分页组件在手机上的优化 */
  .admin-user-footer {
    padding: 8px 4px;
    overflow-x: auto;
  }

  .admin-user-footer :deep(.el-pagination) {
    flex-wrap: wrap;
    justify-content: center;
  }

  .admin-user-footer :deep(.el-pagination__sizes),
  .admin-user-footer :deep(.el-pagination__jump) {
    margin: 4px 0;
  }

  /* 对话框在手机端占满屏幕 */
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 0 auto !important;
  }

  :deep(.el-dialog__body) {
    padding: 15px;
  }
}
</style>